package com.manager.sms;

import com.manager.workflow.WorkFlowConstants;
import com.sms.impl.GSTEngineFactory;
import com.sms.impl.Queue;
import com.sms.pub.MyRunnable;
import com.util.ApplicationUtil;

public class MsgSend extends MyRunnable {
	private GetReport getReport = null;
	public GSTEngineFactory fac;
	public Queue sendQueue = new Queue();

	public void end() {
	}

	public void checkThread() {
		try {
			if (getReport != null
					&& (getReport.getIdle() > getReport.getMaxIdle() || !(getReport
							.isAlive()))) {
				getReport.stop();
				getReport.start();
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * 停止通道上行读取线程,通道下行发送线程,并关闭本线程的连接
	 */
	public void clear() {
		if (getReport != null) {
			try {
				getReport.stop();
			} catch (Exception e) {
			}
		}
	}

	public MsgSend() {
		super("发送线程");
	}

	public void run() {
		System.out.println(getName() + " 线程已开启");
		resetIdle();
		bStop = false;

		fac = GSTEngineFactory.getInstance();

		getReport = new GetReport(fac.getQueue());
		getReport.setMaxIdle(30);

		while (!bStop) {
			resetIdle();
			checkThread();

			try {
				if (fac.getConn() == null) {
					if (fac.loginEngin() == 0) {
						System.out.println("-用户登陆成功连接!");
					} else {
						System.out.println("-用户登陆连接失败!");
						sleep(10000);
						continue;
					}
				}
				if (!sendQueue.isEmpty()) {
					SmsBean smsBean = (SmsBean) sendQueue.pop();

					if (smsBean.phones.length == 1) { // 单发
						fac.setSequenceSMS(smsBean.sequence); // 设置状态报告应答的标志匹配符
						int flag = fac.sendSigleSMS(smsBean.prefix,
								smsBean.phones[0], smsBean.content);
						ApplicationUtil au = new ApplicationUtil();
						if (flag == 0) {
							au.updateSmsState(smsBean.sequence, WorkFlowConstants.SMS_STATUS_2);
							System.out.println("-单发短信成功!");
						}else{
							System.out.println("-单发短信失败!");
							au.updateSmsState(smsBean.sequence, WorkFlowConstants.SMS_STATUS_3);
						}

					} else if (smsBean.phones.length > 1) { // 群发
						int count = fac.sendClusterSMS(smsBean.prefix,
								smsBean.phones, smsBean.content);
						if (count != -1) {
							System.out.println("-群发短信成功!");
						}
					}
				}
				sleep(20);
			} catch (Exception e) {
				sleep(20);
				System.out.println(getName() + " 运行异常:" + e);
			}
		}

		clear();
		System.out.println(getName() + " 线程已关闭");
	}

	public static void main(String[] args) {
		MsgSend msgSend = new MsgSend();
		msgSend.start();

		// 单发
		SmsBean smsBean = new SmsBean();
		smsBean.sequence = 1;
		smsBean.prefix = "888";
		smsBean.phones = new String[] { "15991376822" };
		smsBean.content = "单发测试";
		msgSend.sendQueue.push(smsBean);

//		// 群发
//		smsBean = new SmsBean();
//		smsBean.prefix = "888";
//		smsBean.phones = new String[] { "13800138000", "13800138001" };
//		smsBean.content = "群发测试";
//		msgSend.sendQueue.push(smsBean);
	}
}
